# coding=utf-8
import json

from db.dbhelper import execute_sql_new
from util.pathutil import LOG_DIR
from datetime import datetime


def create_log_file():
    """创建日志文件"""
    if not LOG_DIR.exists():
        LOG_DIR.mkdir()
    # 获取当前时间
    current_day = datetime.now().strftime("%Y-%m-%d")
    log_path = LOG_DIR.joinpath(f"{current_day}.txt")
    if not log_path.exists():
        log_path.touch()
    return log_path


def write_log(log):
    log_path = create_log_file()
    log_obj = log.to_dict()
    log_str = json.dumps(log_obj, indent=4)
    log_str += "\r\n"
    with open(log_path, "a+", encoding="utf-8") as f:
        f.write(log_str)
    sql = "insert into pre_sale_log(log_date, log_msg, log_args) values(%s,%s,%s)"
    param = (datetime.now(), log_str, str(log.args))
    execute_sql_new(sql, param)
